package com.zixuan.gulicollege.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zixuan.gulicollege.common_utils.ResultCode;
import com.zixuan.gulicollege.exception_handler.ConstantExceptionInfo;
import com.zixuan.gulicollege.exception_handler.GuliException;
import com.zixuan.gulicollege.oss.service.OssService;
import com.zixuan.gulicollege.oss.utils.ConstantYmlUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * @ClassName OssServiceImpl
 * @Author by zixuan
 * @Date 2021/5/3 17:29
 */

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 获取oss值
        String endpoint = ConstantYmlUtils.END_POIND;
        String accessKeyId = ConstantYmlUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantYmlUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantYmlUtils.BUCKET_NAME;

        try {
            // 创建OSS实列
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件流
            InputStream is = file.getInputStream();

            // 获取文件名称
            String fileName = file.getOriginalFilename();

            // 生成uuid随机值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            fileName = uuid + fileName;

            // 文件按照日期事件分类
            String dataPath = new DateTime().toString("yyyy/MM/dd");

            fileName = dataPath + "/" + fileName;

            // 调用oss方法实现上传
            ossClient.putObject(bucketName, fileName, is);

            // 关闭OSSClient
            ossClient.shutdown();

            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

            return url;
        } catch (IOException e) {
            e.printStackTrace();
            throw new GuliException(ResultCode.ERROR, ConstantExceptionInfo.FAIL_UPLOAD_IMAGE);
        }
    }
}
